//
//  CheckInclusion.swift
//  LeetCodeDemo
//
//  Created by OS on 2022/6/7.
//

import Foundation

class CheckInclusion {
    func checkInclusion(_ s1: String, _ s2: String) -> Bool {
        let s1 = Array(s1), s2 = Array(s2)
        let n = s1.count, m = s2.count
        if n > m {
            return false
        }
        
        var count1 = [Int](repeating: 0, count: 26)
        var count2 = [Int](repeating: 0, count: 26)
        
        for i in 0..<n {
            let index1 = Int(s1[i].asciiValue ?? 0) - Int(Character("a").asciiValue ?? 0)
            count1[index1] += 1
            let index2 = Int(s2[i].asciiValue ?? 0) - Int(Character("a").asciiValue ?? 0)
            count2[index2] += 1
        }
        if count1 == count2 {
            return true
        }
        
        for i in n..<m {
            
            let index1 = Int(s2[i - n].asciiValue ?? 0) - Int(Character("a").asciiValue ?? 0)
            count2[index1] -= 1
            let index2 = Int(s2[i].asciiValue ?? 0) - Int(Character("a").asciiValue ?? 0)
            count2[index2] += 1
            
            if count1 == count2 {
                return true
            }
            
        }
        
        return false
    }
    
    func test() {
        let res = checkInclusion("asdfghjkl", "qwertyuiopkjhgfdsasdcfvghjk")
        print(res)
    }
}
